﻿using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Caching.Distributed;
using Microsoft.Extensions.Caching.Memory;
using Microsoft.Extensions.Logging;
using StackExchange.Redis;
using System.Text.Json;
using WebCoreAPI.Models;

namespace WebCoreAPI.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class TestController : ControllerBase
    {

        private readonly IMemoryCache cache; // 本地缓存对象
        private readonly IDistributedCache distributedCache; //对于分布式缓存使用的对象，Redis的使用

        public TestController(IMemoryCache cache, IDistributedCache distributedCache)
        {
            this.cache = cache;
            this.distributedCache = distributedCache;
        }

        [HttpGet(Name = "getPerson")]
        public Person GetPerson()
        {
            return new Person(0, "姓名", 20, DateTime.Now);
        }

        [HttpPost]

        public String[] PostPerson(Person person)
        {
            return new String[] { "姓名", person.Name, "创建时间", person.CreateTime.ToString() };
        }

        [HttpPost]

        public ActionResult<int> SumMethod(int a, int b)
        {
            return a + b;
        }

        [HttpGet]
        [ResponseCache(Duration = 60)]
        public ActionResult<DateTime> getCurrentTime()
        {
            return DateTime.Now;
        }


        /// <summary>
        /// 本地缓存的使用
        /// </summary>
        /// <param name="id"></param>
        /// <returns></returns>
        [HttpGet]
        public async Task<ActionResult<Person>> getPersonCacheById(int id)
        {
            var mypers = await cache.GetOrCreateAsync("person" + id, async (e) =>
            {
                await Console.Out.WriteLineAsync("重新调用！");
                e.SlidingExpiration = TimeSpan.FromSeconds(5); //滑动过期时间5秒
                e.AbsoluteExpirationRelativeToNow = TimeSpan.FromSeconds(15); // 设置缓存有效时间为15秒
                return await GetPersonByIdAsync(id);
            });
            return mypers;


        }

        [HttpGet]
        public async Task<ActionResult<Person>> getPersonRedisCacheById(int id)
        {
            Person? person;
            string? redisContent = await distributedCache.GetStringAsync("person" + id);
            if (String.IsNullOrEmpty(redisContent))
            {
                person = await GetPersonByIdAsync(id);
                await distributedCache.SetStringAsync("person" + id, JsonSerializer.Serialize(person));
            }
            else
            {
                person = JsonSerializer.Deserialize<Person>(redisContent);
            }
            return person != null ? person : NotFound("不存在");
        }

        private Task<Person> GetPersonByIdAsync(int id)
        {
            Person myperson = new Person(4, "小小", 10, DateTime.Now);

            switch (id)
            {
                case 0:
                    myperson = new Person(0, "小明", 10, DateTime.Now);
                    break;
                case 1:
                    myperson = new Person(1, "小红", 10, DateTime.Now);
                    break;
                case 2:
                    myperson = new Person(2, "小绿", 10, DateTime.Now);
                    break;
                case 3:
                    myperson = new Person(3, "小黄", 10, DateTime.Now);
                    break;
                default:
                    myperson = new Person(4, "小小", 10, DateTime.Now);
                    break;
            }

            return Task.FromResult(myperson);

        }

    }
}
